use std::collections::HashMap;
use std::sync::Arc;
use tokio::sync::{Mutex, broadcast};
use tokio::time::{Duration, interval};
use tracing::{info, error, debug, warn};
use chrono::{DateTime, Utc};
use serde::{Serialize, Deserialize};

use super::{DeviceManager, DeviceHealth, PerformanceMetrics, AdbError};

/// 监控配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MonitoringConfig {
    pub heartbeat_interval: u64,  // 心跳检测间隔 (秒)
    pub health_check_interval: u64,  // 健康检查间隔 (秒)
    pub performance_threshold: PerformanceThreshold,
    pub alert_config: AlertConfig,
}

/// 性能阈值配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PerformanceThreshold {
    pub cpu_warning: f32,     // CPU使用率警告阈值
    pub cpu_critical: f32,    // CPU使用率严重阈值
    pub memory_warning: f32,  // 内存使用率警告阈值
    pub memory_critical: f32, // 内存使用率严重阈值
    pub battery_low: f32,     // 低电量阈值
    pub temperature_high: f32, // 高温阈值
}

/// 告警配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AlertConfig {
    pub enabled: bool,
    pub email_notifications: bool,
    pub desktop_notifications: bool,
    pub alert_cooldown: u64,  // 告警冷却时间 (秒)
}

/// 监控事件类型
#[derive(Debug, Clone, Serialize)]
pub enum MonitoringEvent {
    PerformanceWarning {
        device_id: String,
        metric: String,
        current_value: f32,
        threshold: f32,
        timestamp: DateTime<Utc>,
    },
    PerformanceCritical {
        device_id: String,
        metric: String,
        current_value: f32,
        threshold: f32,
        timestamp: DateTime<Utc>,
    },
    DeviceHealthChanged {
        device_id: String,
        is_healthy: bool,
        issues: Vec<String>,
        timestamp: DateTime<Utc>,
    },
    MonitoringStarted {
        device_count: usize,
        timestamp: DateTime<Utc>,
    },
    MonitoringStopped {
        timestamp: DateTime<Utc>,
    },
}

/// 设备监控服务
pub struct DeviceMonitoringService {
    config: Arc<Mutex<MonitoringConfig>>,
    active_monitors: Arc<Mutex<HashMap<String, MonitorHandle>>>,
    event_sender: broadcast::Sender<MonitoringEvent>,
    global_monitoring_active: Arc<Mutex<bool>>,
}

/// 单个设备监控句柄
#[derive(Debug)]
struct MonitorHandle {
    device_id: String,
    last_alert_time: Arc<Mutex<HashMap<String, DateTime<Utc>>>>,
    task_handle: tokio::task::JoinHandle<()>,
}

impl Default for MonitoringConfig {
    fn default() -> Self {
        Self {
            heartbeat_interval: 30,
            health_check_interval: 60,
            performance_threshold: PerformanceThreshold {
                cpu_warning: 70.0,
                cpu_critical: 90.0,
                memory_warning: 80.0,
                memory_critical: 95.0,
                battery_low: 20.0,
                temperature_high: 45.0,
            },
            alert_config: AlertConfig {
                enabled: true,
                email_notifications: false,
                desktop_notifications: true,
                alert_cooldown: 300, // 5分钟
            },
        }
    }
}

impl DeviceMonitoringService {
    /// 创建新的监控服务
    pub fn new() -> Self {
        let (event_sender, _) = broadcast::channel(500);
        
        Self {
            config: Arc::new(Mutex::new(MonitoringConfig::default())),
            active_monitors: Arc::new(Mutex::new(HashMap::new())),
            event_sender,
            global_monitoring_active: Arc::new(Mutex::new(false)),
        }
    }

    /// 启动全局监控
    pub async fn start_monitoring(&self, device_manager: Arc<Mutex<DeviceManager>>) -> Result<(), AdbError> {
        info!("Starting global device monitoring");
        
        *self.global_monitoring_active.lock().await = true;
        
        // 获取所有在线设备
        let devices = {
            let manager = device_manager.lock().await;
            manager.get_all_devices().await?
        };
        
        // 为每个设备启动监控
        for device in devices {
            let device_id = device.id.clone();
            if let Err(e) = self.start_device_monitoring(device_id.clone(), device_manager.clone()).await {
                error!("Failed to start monitoring for device {}: {}", device_id, e);
            }
        }
        
        // 发送监控启动事件
        let device_count = {
            let monitors = self.active_monitors.lock().await;
            monitors.len()
        };
        
        let _ = self.event_sender.send(MonitoringEvent::MonitoringStarted {
            device_count,
            timestamp: Utc::now(),
        });
        
        info!("Global monitoring started for {} devices", device_count);
        Ok(())
    }

    /// 为单个设备启动监控
    pub async fn start_device_monitoring(
        &self,
        device_id: String,
        device_manager: Arc<Mutex<DeviceManager>>,
    ) -> Result<(), AdbError> {
        info!("Starting monitoring for device: {}", device_id);
        
        let config = self.config.lock().await.clone();
        let event_sender = self.event_sender.clone();
        let global_active = self.global_monitoring_active.clone();
        let device_id_clone = device_id.clone();
        
        // 创建告警冷却时间管理
        let alert_times = Arc::new(Mutex::new(HashMap::new()));
        let alert_times_task = alert_times.clone();
        
        // 启动监控任务
        let task_handle = tokio::spawn(async move {
            let mut health_interval = interval(Duration::from_secs(config.health_check_interval));
            
            loop {
                health_interval.tick().await;
                
                // 检查全局监控是否仍然活跃
                {
                    let active = global_active.lock().await;
                    if !*active {
                        break;
                    }
                }
                
                // 执行健康检查
                if let Err(e) = Self::perform_health_check(
                    &device_id_clone,
                    &device_manager,
                    &config,
                    &event_sender,
                    &alert_times_task,
                ).await {
                    warn!("Health check failed for device {}: {}", device_id_clone, e);
                }
            }
            
            debug!("Monitoring stopped for device: {}", device_id_clone);
        });
        
        // 保存监控句柄
        let monitor_handle = MonitorHandle {
            device_id: device_id.clone(),
            last_alert_time: alert_times,
            task_handle,
        };
        
        let mut monitors = self.active_monitors.lock().await;
        monitors.insert(device_id, monitor_handle);
        
        Ok(())
    }

    /// 执行设备健康检查
    async fn perform_health_check(
        device_id: &str,
        device_manager: &Arc<Mutex<DeviceManager>>,
        config: &MonitoringConfig,
        event_sender: &broadcast::Sender<MonitoringEvent>,
        alert_times: &Arc<Mutex<HashMap<String, DateTime<Utc>>>>,
    ) -> Result<(), AdbError> {
        debug!("Performing health check for device: {}", device_id);
        
        // 获取设备性能指标
        let performance = {
            let manager = device_manager.lock().await;
            manager.get_device_performance(device_id).await?
        };
        
        let now = Utc::now();
        let threshold = &config.performance_threshold;
        let mut issues = Vec::new();
        let mut is_healthy = true;
        
        // CPU使用率检查
        if performance.cpu_usage >= threshold.cpu_critical {
            issues.push(format!("Critical CPU usage: {:.1}%", performance.cpu_usage));
            is_healthy = false;
            
            Self::send_alert_if_allowed(
                event_sender,
                alert_times,
                "cpu_critical",
                config.alert_config.alert_cooldown,
                MonitoringEvent::PerformanceCritical {
                    device_id: device_id.to_string(),
                    metric: "CPU".to_string(),
                    current_value: performance.cpu_usage,
                    threshold: threshold.cpu_critical,
                    timestamp: now,
                },
            ).await;
        } else if performance.cpu_usage >= threshold.cpu_warning {
            issues.push(format!("High CPU usage: {:.1}%", performance.cpu_usage));
            
            Self::send_alert_if_allowed(
                event_sender,
                alert_times,
                "cpu_warning",
                config.alert_config.alert_cooldown,
                MonitoringEvent::PerformanceWarning {
                    device_id: device_id.to_string(),
                    metric: "CPU".to_string(),
                    current_value: performance.cpu_usage,
                    threshold: threshold.cpu_warning,
                    timestamp: now,
                },
            ).await;
        }
        
        // 内存使用率检查
        if performance.memory_usage >= threshold.memory_critical {
            issues.push(format!("Critical memory usage: {:.1}%", performance.memory_usage));
            is_healthy = false;
            
            Self::send_alert_if_allowed(
                event_sender,
                alert_times,
                "memory_critical",
                config.alert_config.alert_cooldown,
                MonitoringEvent::PerformanceCritical {
                    device_id: device_id.to_string(),
                    metric: "Memory".to_string(),
                    current_value: performance.memory_usage,
                    threshold: threshold.memory_critical,
                    timestamp: now,
                },
            ).await;
        } else if performance.memory_usage >= threshold.memory_warning {
            issues.push(format!("High memory usage: {:.1}%", performance.memory_usage));
            
            Self::send_alert_if_allowed(
                event_sender,
                alert_times,
                "memory_warning",
                config.alert_config.alert_cooldown,
                MonitoringEvent::PerformanceWarning {
                    device_id: device_id.to_string(),
                    metric: "Memory".to_string(),
                    current_value: performance.memory_usage,
                    threshold: threshold.memory_warning,
                    timestamp: now,
                },
            ).await;
        }
        
        // 电池电量检查
        if let Some(battery_level) = performance.battery_level {
            if battery_level <= threshold.battery_low {
                issues.push(format!("Low battery: {:.1}%", battery_level));
                
                Self::send_alert_if_allowed(
                    event_sender,
                    alert_times,
                    "battery_low",
                    config.alert_config.alert_cooldown,
                    MonitoringEvent::PerformanceWarning {
                        device_id: device_id.to_string(),
                        metric: "Battery".to_string(),
                        current_value: battery_level,
                        threshold: threshold.battery_low,
                        timestamp: now,
                    },
                ).await;
            }
        }
        
        // 发送健康状态更新事件
        let _ = event_sender.send(MonitoringEvent::DeviceHealthChanged {
            device_id: device_id.to_string(),
            is_healthy,
            issues,
            timestamp: now,
        });
        
        Ok(())
    }

    /// 发送告警 (带冷却时间控制)
    async fn send_alert_if_allowed(
        event_sender: &broadcast::Sender<MonitoringEvent>,
        alert_times: &Arc<Mutex<HashMap<String, DateTime<Utc>>>>,
        alert_key: &str,
        cooldown_seconds: u64,
        event: MonitoringEvent,
    ) {
        let now = Utc::now();
        let mut times = alert_times.lock().await;
        
        let should_send = if let Some(last_time) = times.get(alert_key) {
            let duration = now.signed_duration_since(*last_time);
            duration.num_seconds() >= cooldown_seconds as i64
        } else {
            true
        };
        
        if should_send {
            times.insert(alert_key.to_string(), now);
            let _ = event_sender.send(event);
            debug!("Alert sent for key: {}", alert_key);
        } else {
            debug!("Alert suppressed for key: {} (cooldown active)", alert_key);
        }
    }

    /// 停止设备监控
    pub async fn stop_device_monitoring(&self, device_id: &str) -> Result<(), AdbError> {
        info!("Stopping monitoring for device: {}", device_id);
        
        let mut monitors = self.active_monitors.lock().await;
        if let Some(monitor) = monitors.remove(device_id) {
            monitor.task_handle.abort();
            info!("Monitoring stopped for device: {}", device_id);
        }
        
        Ok(())
    }

    /// 停止所有监控
    pub async fn stop_all_monitoring(&self) {
        info!("Stopping all device monitoring");
        
        *self.global_monitoring_active.lock().await = false;
        
        let mut monitors = self.active_monitors.lock().await;
        for (device_id, monitor) in monitors.drain() {
            monitor.task_handle.abort();
            debug!("Stopped monitoring for device: {}", device_id);
        }
        
        // 发送监控停止事件
        let _ = self.event_sender.send(MonitoringEvent::MonitoringStopped {
            timestamp: Utc::now(),
        });
        
        info!("All monitoring stopped");
    }

    /// 更新监控配置
    pub async fn update_config(&self, new_config: MonitoringConfig) -> Result<(), AdbError> {
        info!("Updating monitoring configuration");
        
        let mut config = self.config.lock().await;
        *config = new_config;
        
        // TODO: 动态更新运行中的监控任务间隔
        // 当前实现需要重启监控来应用新配置
        
        Ok(())
    }

    /// 获取当前配置
    pub async fn get_config(&self) -> MonitoringConfig {
        let config = self.config.lock().await;
        config.clone()
    }

    /// 获取监控状态
    pub async fn get_monitoring_status(&self) -> serde_json::Value {
        let active_count = {
            let monitors = self.active_monitors.lock().await;
            monitors.len()
        };
        
        let is_active = *self.global_monitoring_active.lock().await;
        let config = self.get_config().await;
        
        serde_json::json!({
            "global_active": is_active,
            "monitored_devices": active_count,
            "heartbeat_interval": config.heartbeat_interval,
            "health_check_interval": config.health_check_interval,
            "alerts_enabled": config.alert_config.enabled,
            "last_update": Utc::now().to_rfc3339(),
        })
    }

    /// 订阅监控事件
    pub fn subscribe_events(&self) -> broadcast::Receiver<MonitoringEvent> {
        self.event_sender.subscribe()
    }

    /// 获取设备监控统计
    pub async fn get_monitoring_stats(&self) -> serde_json::Value {
        let monitors = self.active_monitors.lock().await;
        let config = self.config.lock().await;
        
        serde_json::json!({
            "total_monitored": monitors.len(),
            "monitoring_active": *self.global_monitoring_active.lock().await,
            "config": {
                "heartbeat_interval": config.heartbeat_interval,
                "health_check_interval": config.health_check_interval,
                "alerts_enabled": config.alert_config.enabled
            },
            "uptime": "N/A", // TODO: 实现监控运行时间统计
        })
    }

    /// 手动触发设备健康检查
    pub async fn trigger_health_check(
        &self,
        device_id: &str,
        device_manager: Arc<Mutex<DeviceManager>>,
    ) -> Result<DeviceHealth, AdbError> {
        info!("Manual health check for device: {}", device_id);
        
        let performance = {
            let manager = device_manager.lock().await;
            manager.get_device_performance(device_id).await?
        };
        
        let config = self.config.lock().await;
        let threshold = &config.performance_threshold;
        let mut issues = Vec::new();
        let mut is_healthy = true;
        
        // 性能分析
        if performance.cpu_usage >= threshold.cpu_critical {
            issues.push("Critical CPU usage".to_string());
            is_healthy = false;
        } else if performance.cpu_usage >= threshold.cpu_warning {
            issues.push("High CPU usage".to_string());
        }
        
        if performance.memory_usage >= threshold.memory_critical {
            issues.push("Critical memory usage".to_string());
            is_healthy = false;
        } else if performance.memory_usage >= threshold.memory_warning {
            issues.push("High memory usage".to_string());
        }
        
        if let Some(battery) = performance.battery_level {
            if battery <= threshold.battery_low {
                issues.push("Low battery".to_string());
            }
        }
        
        let health = DeviceHealth {
            device_id: device_id.to_string(),
            is_healthy,
            performance,
            last_check: Utc::now(),
            issues,
        };
        
        // 发送健康状态事件
        let _ = self.event_sender.send(MonitoringEvent::DeviceHealthChanged {
            device_id: device_id.to_string(),
            is_healthy: health.is_healthy,
            issues: health.issues.clone(),
            timestamp: health.last_check,
        });
        
        Ok(health)
    }

    /// 获取监控事件历史
    pub async fn get_monitoring_history(&self, _limit: Option<usize>) -> Vec<MonitoringEvent> {
        // TODO: 实现事件历史存储和检索
        // 当前返回空列表，后续可以添加持久化存储
        Vec::new()
    }
}